import 'package:dio/adapter.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'main2.dart';
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'Util.dart';
void main() {
  runApp(MyApp());
//  ShareHandle.instance.proxy = "PROXY 192.168.1.10:8888";
ShareHandle.instance.shouldUseCamara = true;
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primaryColor: Color(0xff0642ec),
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 强制横屏
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
//    loadData();
  }
  void loadData(){
    Dio().get("http://www.baidu.com").then((value) => print(value.toString()));
  }
  _getIPAddress() async {
    print("1");
    HttpClient client = new HttpClient();
    print("2");
    client.getUrl(Uri.parse("http://www.example.com/"))
        .then((HttpClientRequest request) {
      print("3");
      return request.close();
    })
        .then((HttpClientResponse response) {
      // Process the response
      print("4");
      print(response.statusCode);
    }).catchError((e) {
      print("永远不会到达");
    });;
    print("5");
  }
  /// 实际上的真正跳转
  realPush(qr) {

    String block_key = qr;
    Map<String,String> dic = {"api_key":"xQITe6bZFUrmeJbkcKgkUzajUI6FGLA","block_key":block_key,"lang":"en","serial_no":"","device_name":""};
    var dio = Dio();
    if (ShareHandle.instance.proxy.length > 0){
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client){
        client.findProxy = (uri) {
          return ShareHandle.instance.proxy;
        };
      };
    }
    dio.post("http://estate.homeon.hk/api/visitor_staff/assign",data:FormData.fromMap(dic)).then((value){
      print(value.toString());
      SharedPreferences.getInstance().then((v1) {
        final result = value.toResult();
        if (result.item2){
          v1.setString("buildings", (result.item1["container"] as Map).toJSONString());
          final buildings = result.item1["container"];
          Navigator.push( context, MaterialPageRoute(settings:RouteSettings(name: "MyHome2Page"),builder: (context) => MyHome2Page(title: "${buildings["estate_name"] ?? ""}${buildings["block"] ?? ""}",para: {"block_key":block_key})),);
        }
      });
    });
  }

  Future scan() async {
    if (ShareHandle.instance.shouldUseCamara){
      var result = await BarcodeScanner.scan();
      if (result.type == ResultType.Barcode) {
        showDialog<Null>(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return new AlertDialog(
                title: new Text(result.rawContent),
                //可滑动
                content: new SingleChildScrollView(
                  child: new ListBody(
                    children: <Widget>[
                      new Text(''),
                    ],
                  ),
                ),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text('确定'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      realPush(result.rawContent);
                    },
                  ),
                  new FlatButton(
                    child: new Text('取消'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            });
      }

      print(result.type); // The result type (barcode, cancelled, failed)
      print(result.rawContent); // The barcode content
      print(result.format); // The barcode format (as enum)
      print(result
          .formatNote); // If a unknown format was scanned this field contains a note
    }else{
      realPush("kA4ff/DdRU/fVsG6G+hPeH+YDQ");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(
              image: AssetImage("assets/images/landing_icon_visitor.png"),
            ),
            SizedBox(height: 20),
            FlatButton(
                onPressed: scan,
                child: Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Image(
                      image: AssetImage("assets/images/btn_bg_scan-_qr.png"),
                    ),
                    Text("掃描屋苑二維碼",style: new TextStyle(color: Color.fromARGB(255, 255, 255, 255),fontSize: 18),)
                  ],
                )
            )
          ],
        ),
      ),
    );
  }
}
